package cn.icare.cms;


import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.AttributedString;

public class ImageUtil {
    private Font font = null;
    private Graphics2D g = null;

    /**
     * @param img1
     * @param orignPrice 原价
     * @param newPrice   现价
     * @return BufferedImage
     * @throws IOException
     */
    public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, String orignPrice, String newPrice,String fontDir)
            throws IOException {
        Font newfont = loadFont(fontDir,36);
        int w1 = img1.getWidth();
        int h1 = img1.getHeight();
        int w2 = img2.getWidth();
        int h2 = img2.getHeight();
        //分享图微信要求宽高比是5：4，因此宽度不变的情况把高度截取掉
        int newHeight= Math.round(w1*new Float(0.8));
        BufferedImage newImage = new BufferedImage(w1, newHeight, BufferedImage.TYPE_INT_RGB);// 新的图
        Graphics2D graphics = (Graphics2D) newImage.getGraphics();
        graphics.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());
        graphics.drawImage(img1, 0, 0, null);
        graphics.drawImage(img2, (newImage.getWidth()) / 2 - (w2 / 2), newImage.getHeight() - h2,
                null);
        graphics.setFont(newfont);
        graphics.setColor(Color.white);
        String newtitle = "￥" + newPrice + " ";
        graphics.drawString(newtitle, 20, newImage.getHeight() - 10);

        if (StringUtil.isNotEmpty(orignPrice)) {
            int width = graphics.getFontMetrics(newfont).stringWidth(newtitle);
            String orignTitle = "￥" + orignPrice;

            Font orignfont =loadFont(fontDir,24);;
            AttributedString as = new AttributedString(orignTitle);
            as.addAttribute(TextAttribute.FONT, orignfont);
            as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
            graphics.drawString(as.getIterator(), 20+width + 10, newImage.getHeight() - 10);
        }

        return newImage;
    }

    public static Font loadFont(String fontFileName, float fontSize)  //第一个参数是外部字体名，第二个是字体大小
    {
        try
        {
            File file = new File(fontFileName);
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
            aixing.close();
            return dynamicFontPt;
        }
        catch(Exception e)//异常处理
        {
            e.printStackTrace();
            return new java.awt.Font("宋体", Font.PLAIN, 14);
        }
    }
}
